package com.huo.importdata.service;

import com.huo.annotation.TaskLogAnnotation;
import com.huo.common.enumtype.FtpFileStatusEnum;
import com.huo.filestransport.dao.FtpFileInfoDao;
import com.huo.filestransport.entity.FtpFileInfoEntity;
import com.huo.filestransport.vo.FtpServerInfo;
import com.huo.importdata.dao.DepositMapper;
import com.huo.importdata.entity.Deposit;
import com.huo.util.DateUtils;
import com.huo.util.FileSplit;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
@DisallowConcurrentExecution
public class ImportDataDpfmService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private FtpFileInfoDao ftpFileInfoDao;
    @Autowired
    private DepositMapper depositMapper;
    @Autowired
    private FileSplit fileSplit;
    @Autowired
    private FtpServerInfo ftpServerInfo;


    private final static int insertBatchNum = 100;

    private final static int splipFileNum = 10;

    @TaskLogAnnotation
    public void importDpfm(){
        String dataDate = DateUtils.DateCount(ftpServerInfo.getDelayTime(),"yyyy-MM-dd");
        importDpfm(dataDate);
    }

    @TaskLogAnnotation
    public void importDpfm(String dataDate){
        logger.info("导入dpfm数据开始" );
        try {
            FtpFileInfoEntity record = new FtpFileInfoEntity();
            record.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_UNZIP.getCode());
            record.setFtpfilename("S01_DPFM22.zip");
            record.setDataDateStr(dataDate);
            FtpFileInfoEntity ffe = ftpFileInfoDao.selectBySelective(record);
            if(ffe != null){
                //将表中数据删除
                depositMapper.truncateTableDeposit();
                String unzipfilePaht = ffe.getUnzipfilepath();
                logger.info("拆分{}文件开始",unzipfilePaht );
                fileSplit.splitFile(unzipfilePaht,splipFileNum);
                logger.info("拆分{}文件结束,拆分文件数{}",unzipfilePaht,splipFileNum );
                logger.info("多线程插入数据开始,线程数：{}", splipFileNum);
                long startT = System.currentTimeMillis();
                final CountDownLatch latch = new CountDownLatch(splipFileNum);
                for(int i = 1 ; i <= splipFileNum ; i++){
                    int finalI = i;
                    Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            logger.info("线程 {}开始",finalI);
                            BufferedInputStream fis = null;
                            BufferedReader reader = null;
                            try {
                                long start = System.currentTimeMillis();
                                File file = new File(unzipfilePaht + finalI);
                                fis = new BufferedInputStream(new FileInputStream(file));
                                reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),20*1024*1024);
                                String line = "";
                                int dataNum = 0;
                                //插入次数
                                int insertNum = 0;
                                List<Deposit> list = new ArrayList<>();
                                while((line = reader.readLine()) != null){
                                    String[] str = line.split("\u001B");
                                    //System.out.println(Arrays.toString(str));
                                    Deposit d = new Deposit();
                                    d.setAccNo(str[0]);
                                    d.setLocalCode(str[2]);
                                    d.setSubCode(str[3]);
                                    d.setAccType(str[4]);
                                    d.setHdflag(str[5]);
                                    d.setCloseflag(str[6]);
                                    d.setProductId(str[9]);
                                    d.setOpenDate(str[10]);
                                    d.setStartDate(str[11]);
                                    d.setEndDate(str[12]);
                                    d.setBalance(new BigDecimal(str[15]));
                                    d.setUpdateDate(new Date());
                                    d.setFix(d.getLocalCode().substring(0,3));
                                    d.setAccs(str[1]);
                                    list.add(d);
                                    if(list.size() == insertBatchNum){
                                        depositMapper.insertBatch(list);
                                        list.clear();
                                        insertNum ++ ;
                                    }
                                    dataNum ++;
                                }
                                if(dataNum != insertNum * insertBatchNum){
                                    depositMapper.insertBatch(list);
                                }
                                long end = System.currentTimeMillis();
                                logger.info("线程 {}保存数据{},运行时间{}",finalI,dataNum,end-start);
                                latch.countDown();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }finally {
                                try {
                                    if(reader != null){
                                        reader.close();
                                    }
                                    if(fis != null){
                                        fis.close();
                                    }

                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    t.start();
                }
                latch.await();
                long endT = System.currentTimeMillis();
                logger.info("多线程插入数据结束,导入数据时间：{}",endT-startT);
                FtpFileInfoEntity param = new FtpFileInfoEntity();
                param.setId(ffe.getId());
                param.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_IMPORT.getCode());
                param.setUpdatetime(new Date());
                ftpFileInfoDao.updateByPrimaryKeySelective(param);
            }else{
                logger.info("未查询到S01_DPFM22.zip文件" );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("导入dpfm数据结束" );

    }
}
